﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AntdUI;

namespace TestPressure
{
    public partial class DevicePointManageForm: BaseForm
    {
        #region 属性

        private DevicePoint? obj;

        /// <summary>设备
        /// 
        /// </summary>
        public DeviceItem? item;

        #endregion

        #region 自定义方法

        /// <summary>寄存器类型
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string intToRegisterTypeString(int type)
        {
            string registerType = "";
            if (type == 1)
            {
                registerType = "DI";
            }
            else if (type == 2)
            {
                registerType = "DO";
            }
            else if (type == 3)
            {
                registerType = "InputRegister";
            }
            else if (type == 4)
            {
                registerType = "HoldingRegister";
            }
            return registerType;
        }

        /// <summary>设备列表
        /// 
        /// </summary>
        public void LoadList()
        {
            if (item is not null)
            {
                bool res = CheckDeviceExistWithNumber(item.deviceNumber);
                if (!res)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Close();
                        this.Dispose();
                    }));
                    
                    return;
                }
                Dictionary<string, object> where = new Dictionary<string, object>();
                where["device_number"] = item.deviceNumber.ToString();
                List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
                UpdateTable(list);
            }
            else
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    DeviceManageForm frm = (DeviceManageForm)this.Owner;
                    Alert.Error("无法获取设备信息", frm);
                    this.Close();
                    this.Dispose();
                }));
            }
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateTable(List<DevicePoint> list)
        {
            var antItemList = new List<DevicePointItem>();
            foreach (DevicePoint item in list)
            {
                string range = item.range_min.ToString() + "-" + item.range_max.ToString();
                string outValue = item.out_min.ToString() + "-" + item.out_max.ToString();
                string alarm = item.alarm_hight.ToString() + "-" + item.alarm_low.ToString();
                string registerType = intToRegisterTypeString(item.register_type);

                antItemList.Add(new DevicePointItem(item.device_number, item.device_name, item.point_number, 
                                                    item.point_name, item.point_address, range, outValue, item.amend, 
                                                    alarm, item.error_range, item.unit, registerType));
            }
            Table1.DataSource = antItemList;
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private DevicePoint? DevicePointWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["point_number"] = number;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist(int number)
        {
            obj = DevicePointWithNumber(number);
            if (obj == null)
            {
                LoadList();
                string msg = String.Format("【{0}】编号设备点位不存在", number);
                Error(msg);
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>判断设备是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckDeviceExistWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["device_number"] = number;
            List<Device> list = SqlSugarHelper.Inquireable<Device>(where);
            
            if (list.Count == 0)
            {
                string msg = String.Format("【{0}】编号设备不存在，无法编辑点位", number);
                Error(msg);
                return false;
            }
            else
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    Device device = list[0];
                    this.Header.Text = "【" + device.device_name + "】" + "设备点位管理";
                }));
                return true;
            }
        }

        #endregion

        #region 系统方法
        public DevicePointManageForm()
        {
            InitializeComponent();
            this.EnableMove = false;
            //this.FullScreen = true;
        }

        private void DeviceManageForm_Load(object sender, EventArgs e)
        {
            this.StackPanel1.Top = this.Header.Bottom;
            this.StackPanel1.Left = this.Header.Left;
            this.StackPanel1.Width = this.Width;
            this.Table1.Top = this.StackPanel1.Bottom;
            this.Table1.Left = this.Header.Left;
            this.Table1.Width = this.Width;
            this.Table1.Height = this.Height - this.StackPanel1.Height - 10;
            this.WindowState = FormWindowState.Maximized;
            Table1.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("device_number","设备编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("device_name","设备名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_number","点位编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_name","点位名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_address","点位地址"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("range","量程范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("outValue","输出范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("alarm","报警范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("error_range","判断范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("unit","数据单位"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("register_type","寄存器类型"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("operation","操作"){ Fixed=true,Width="auto",ColAlign=AntdUI.ColumnAlign.Center}
            };
            Spin.Config config = new Spin.Config
            {
                Text = "正在加载中...",
            };
            Table1.Spin(config, () =>
            {
                LoadList();
            }, () =>
            {

            });
        }
        /// <summary>添加设备点位
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddDevicePointButton_Click(object sender, EventArgs e)
        {
            AddDevicePointForm frm = new AddDevicePointForm();
            frm.item = item;
            frm.Owner = this;
            frm.ShowDialog();
        }
        
        /// <summary>点击操作按钮
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is DevicePointItem data)
            {
                AntdUI.CellLink link = e.Btn;
                if (link.Id == "edit")
                {
                    bool res = CheckSelectedRowExist(data.point_number);
                    if (!res)
                    {
                        return;
                    }
                    if (obj is not null)
                    {
                        
                    }
                    else
                    {
                        
                        Error("编辑设备点位失败");
                    }
                }
                else if (link.Id == "delete")
                {
                    bool res = CheckSelectedRowExist(data.point_number);
                    if (!res)
                    {
                        return;
                    }
                    string msg = string.Format("您确定要删除【{0}】设备点位吗？",data.point_name);
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", msg)
                    {
                        OnOk = config =>
                        {
                            if (obj is not null)
                            {
                                List<DevicePoint> list = new List<DevicePoint>();
                                list.Add(obj);
                                int deleteRes = SqlSugarHelper.Deleteable(list);
                                if (deleteRes > 0)
                                {
                                    LoadList();
                                }
                                else
                                {
                                    Error("删除设备点位失败");
                                }
                            }
                            else
                            {
                                Error("删除设备点位失败");
                            }
                            return true;
                        },
                    });
                }
                else if (link.Id == "point")
                {
                }
            }
        }

        #endregion
    }
}
